package com.xuzimian.globaldemo.spring.springwebsocket.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;

/**
 * WebSocket Config.
 *
 * @author <a href="https://waylau.com">Way Lau</a>
 * @since 1.0.0 2018年4月2日
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketMessageConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS(); // 当浏览器不支持websocket时，使用 SockJS
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //目标以"/app"开头的消息应该被路由到消息处理方法
        config.setApplicationDestinationPrefixes("/app");
        //目标以"/topic"开头的消息应该被路由到消息代理，消息代理将消息广播到订阅特定主题的所有连接刻划断
        config.enableSimpleBroker("/topic");

        /**
         * 启用全功能外部Broker
         * config.enableStompBrokerRelay("/topic","/queue");
         */

    }

    /**
     * 配置发送消息时间，和缓冲多少数据,传输的消息最大限制。
     * @param registry
     */
    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        registry.setSendTimeLimit(15 * 1000)
                .setSendBufferSizeLimit(512 * 1024)
        .setMessageSizeLimit(128* 1024 );
    }

    /**
     * 注册拦截器，用于拦截每个传入或传出的消息
     *
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // registration.setInterceptors(new MyChannelInterceptor());
    }

}
